﻿using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEvent = UnityEngine.EventSystems;

public static partial class Utility
{
    /// <summary>
    /// 事件监听器工具库
    /// </summary>
    public static class EventTrigger
    {

        /// <summary>
        /// 注册监听事件
        /// </summary>
        /// <param name="eventTrigger"></param>
        /// <param name="triggerType"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public static UnityEvent.EventTrigger.Entry AddListener(
            UnityEvent.EventTrigger eventTrigger,
            EventTriggerType triggerType,
            UnityAction<BaseEventData> action, bool rm = false)
        {
            if (eventTrigger.triggers == null)
            {
                eventTrigger.triggers = new List<UnityEvent.EventTrigger.Entry>();
            }

            UnityEvent.EventTrigger.Entry entry = null;
            for (int i = 0; i < eventTrigger.triggers.Count; i++)
            {
                var trigger = eventTrigger.triggers[i];
                if (trigger.eventID == triggerType)
                {
                    entry = trigger;
                    break;
                }
            }

            if (entry == null)
            {
                entry = new UnityEvent.EventTrigger.Entry();
                entry.eventID = triggerType;
                eventTrigger.triggers.Add(entry);
            }

            // 避免重复添加
            if (rm)
                entry.callback.RemoveListener(action);
            entry.callback.AddListener(action);

            return entry;
        }
    }
}


